package com.example.rlw.mvpplugintest.mvp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.rlw.mvpplugintest.prompt.LoadingCallback;
import com.example.rlw.mvpplugintest.utils.AtomsUtils;
import com.example.rlw.mvpplugintest.utils.ErrorCodeUtills;
import com.example.rlw.mvpplugintest.utils.NotificationUtils;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;

import java.lang.reflect.ParameterizedType;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by rlw on 2018/10/12.
 * Fragment 基类
 */

public abstract class MVPBaseFragment<V extends BaseView, T extends BasePresenterImpl<V>> extends Fragment implements BaseView, Callback.OnReloadListener {
    public T mPresenter;
    private Unbinder mUnBinder;
    private LoadService mLoadService;
    //view是否被创建
    private boolean isViewCreate = false;
    //view是否被用户可见
    private boolean isViewVisible = false;
    //是否是第一次加载数据
    private boolean isFrist = true;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPresenter = getInstance(this, 1);
        if (mPresenter != null) {
            mPresenter.attachView((V) this);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), null);
        mUnBinder = ButterKnife.bind(this, view);
        //freagment 中 注册loadService
        mLoadService = LoadSir.getDefault().register(view, this);
        mLoadService.showSuccess();
        return mLoadService.getLoadLayout();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        isViewCreate = true;
        initData(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isViewVisible) { // 对用户可见
            visibleToUser();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isViewVisible = isVisibleToUser;
        if (isVisibleToUser && isViewCreate) {
            visibleToUser();
        }
    }

    /**
     * 向用户展示数据
     */
    protected void visibleToUser() {
        // 下边是Fragment懒加载
//        if (isFrist) {
//            loadData();
//            isFrist = false;
//        }

        // 下边是每当当前Fragment对用户可见都进行加载数据
        loadData();
    }

    /**
     * 加载数据
     */
    public abstract void loadData();

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        mUnBinder.unbind();
    }

    @Override
    public Context getContext() {
        return super.getContext();
    }

    /**
     * 初始化布局
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 初始化数据
     *
     * @param savedInstanceState
     */
    protected abstract void initData(@Nullable Bundle savedInstanceState);

    /**
     * 打开 activity 无参
     *
     * @param targetActivity
     */
    protected void openActivity(Class<T> targetActivity) {
        openActivity(targetActivity, null);
    }

    /**
     * 带参 跳转activity
     *
     * @param activity
     * @param bundle
     */
    protected void openActivity(Class<T> activity, Bundle bundle) {
        Intent intent = new Intent(getContext(), activity);
        if (bundle != null) {
            intent.putExtra("bundle", bundle);
        }
        startActivity(intent);
    }

    /**
     * 接收上个页面传过来的值
     *
     * @param bundle
     */
    protected void initParms(Bundle bundle) {
    }

    public <T> T getInstance(Object o, int i) {
        try {
            return ((Class<T>) ((ParameterizedType) (o.getClass()
                    .getGenericSuperclass())).getActualTypeArguments()[i])
                    .newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassCastException e) {
            e.printStackTrace();
        } catch (java.lang.InstantiationException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void showLoadingView() {
        mLoadService.showCallback(LoadingCallback.class);
    }

    @Override
    public void showSuccessView(String msg) {
        mLoadService.showSuccess();
        AtomsUtils.makeText(getContext(), msg);
    }

    @Override
    public void showFailureView(int code, String msg) {
        ErrorCodeUtills.disposeEorCode(code, msg, getContext(), mLoadService);
    }

    @Override
    public void onReload(View v) {
        // 当重试时 需重写 该方法
    }
    @Override
    public void onProgress(long totalSize, long downSize) {
        int progress = (int) ((downSize / (double) totalSize) * 100);
        //更新进度条
        NotificationUtils.updateProgress(2, progress);
    }
}
